<template>
  <div>
    <div style="padding-bottom: 10px; padding-top: 10px; padding-left: 10px;">
      <el-input v-model="name" placeholder="请输入搜索内容" style="width: 20%;" clearable/>
      <el-button type="primary" style="margin-left: 5px" :icon="Search" @click="load">Search</el-button>
    </div>
    <div class="demo-image">
      <!-- 商品放置区 -->
      <div v-for="data in this.tableData" class="block">
        <el-image style="width: 100px; height: 100px;" :src="data.image1"/>
        <el-link  @click="$router.push({path : '/goodsMess',query:{id:data.id}})" :underline="false">{{ data.description }}</el-link>
        <div style="text-align: right; padding-right: 5px;"><i @click="send(data.userId)" style="margin-left: 10px; margin-top: 1px; font-size: 20px; cursor: pointer"><el-icon><ChatDotRound /></el-icon></i> ¥ {{ data.price }}</div>
      </div>
    </div>

    <el-dialog
    v-model="this.dialogVisible1"
    title="消息"
    width="30%"
    :before-close="handleClose"
  >
    <span>有人请求聊天</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="this.dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="messPage(this.perpor)">
          接受
        </el-button>
      </span>
    </template>
  </el-dialog>

    <el-dialog
    v-model="this.dialogVisible"
    title="提示"
    width="30%"
    :before-close="handleClose"
  >
    <span>点击跳转聊天界面</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="this.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="messPage(this.chatUser)">
          跳转
        </el-button>
      </span>
    </template>
  </el-dialog>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

  </div>
  
</template>

<script>
  import { Search } from '@element-plus/icons-vue';
  import request from '../utils/request';
  import {ref} from 'vue'
  let socket;
  export default{
    data(){
      return {
        goods: {},
        dialogVisible: false,
        name: '',
        total: 0,
        currentPage: 1,
        pageSize: 20,
        tableData: [
          
        ],
        user: {},
        token: sessionStorage.getItem("token"),
        fit : 'scale-down',
        url : '/OIP-C.jfif/',
        activeIndex : ref('1'),
        circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        user: {},
        isCollapse: false,
        users: [],
        chatUser: '',
        text: "",
        messages: [],
        content: '',
        waitS: false,
        dialogVisible: false,
        dialogVisible1: false,
        perpor: {},
        buyser: {}
      }
    },
    created(){
      this.load()
      this.user = sessionStorage.getItem("user") ? JSON.parse(sessionStorage.getItem("user")) : {}
      let username = this.user.id;
      console.log(this.user.username)
      let _this = this;
      let socketUrl = "ws://localhost:8081/imserver/" + username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data)
          let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
          
          if (data.users) {  // 获取在线人员信息
            _this.users = data.users.filter(user => user.username !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            if (data.from) {
              console.log("我会进来")
              _this.messages.push(data)
              // 构建消息内容
              _this.createContent(data.from, null, data.text)
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
    },
    methods:{
      messPage(perpor){
        sessionStorage.setItem("perpor",perpor)
        this.$router.push("/im")
      },
      send(id) {
        this.chatUser = id
        if (!this.chatUser) {
          this.$message({type: 'warning', message: "请选择聊天对象"})
          return;
        }
          if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
          } else {
            console.log("您的浏览器支持WebSocket");
            //友好提示，等待对方接受
            this.dialogVisible = true
            // 组装待发送的消息 json
            // {"from": "zhang", "to": "admin", "text": "聊天文本"}
            let message = {from: this.user.id, to: this.chatUser, text: 111111}
            socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
            this.messages.push({user: this.user.id, text: 111111})
            // 构建消息内容，本人消息
            // this.createContent(null, this.user.username, this.text)
            this.text = '';
          }
      },
      createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
        let html
        // 当前用户消息
        if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
          html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
              "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
              "    <div class=\"tip left\">" + text + "</div>\n" +
              "  </div>\n" +
              "  <div class=\"el-col el-col-2\">\n" +
              "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
              "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
              "  </span>\n" +
              "  </div>\n" +
              "</div>";
        } else if (remoteUser) {
          if (text == 111111){
            this.perpor = remoteUser
            this.dialogVisible1 = true
          }
        }
      },
      load() {
        request.get("/goods/list", {
          headers:{
            'token':sessionStorage.getItem("token")
          },
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            name: this.name
          }
        }).then(res => {
          this.tableData = res.data.records
          this.total = res.data.total
        })
      },
      add: function(){
        this.dialogVisible = true;
        this.form = {}
      },
      handleEdit(row) {
        this.form = JSON.parse(JSON.stringify(row));
        this.dialogVisible = true
      },
      handleSizeChange: function (pageSize) { //改变每页大小时触发
        this.pageSize = pageSize;
        this.load()
      },
      handleCurrentChange: function (pageNum) {  //改变当前页数时触发
        this.currentPage = pageNum;
        this.load()
      },
    }

  }
  
</script>

<style>
.dialog-footer button:first-child {
  margin-right: 10px;
}
.paginationClass {
  padding-top: 20px;
  min-height: auto;
  /* bottom: 0; */
  height: 20px;
  width: 100%;
  text-align: center;
}
.demo-image .block {
  padding: 0 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 20%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image .block:last-child {
  border-right: none;
}
.demo-image .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>